/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define(['durandal/system'],
    function (system) {

        // unique naming for unamed callbacks
        var _nameCounter = 0;
        // processes cache
        var _processes = {};

        return {
            // register a new callback with it's id
            registerFinalProcess: register,
            finalCompositionComplete: processFinal
        };

        /**
         * register a new callback to be called at the end of all compositions
         */
        function register(processName, callback) {
            processName = processName || '_noname' + _nameCounter++;
            _processes[processName] = callback;
        }

        /**
         * Called by composition.js > endComposition to call all registered callback
         */
        function processFinal() {
            _.each(_.pairs(_processes), function(pair) {
                try {
                    if (typeof pair[1] === 'function') {
                        pair[1]();
                    }
                    delete _processes[pair[0]];
                } catch(e) {
                    system.log('error:could not call ' + pair[0]);
                }
            });

            _processes = {};
            _nameCounter = 0;
        }

    });